<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
      <el-form-item label="推荐类型" prop="recommend">
        <el-radio-group v-model="formData.recommend">
          <el-radio :label="0" class="radio">不推荐</el-radio>
          <el-radio :label="1">精选</el-radio>
          <el-radio :label="2">爆款</el-radio>
          <el-radio :label="3">新品</el-radio>
          <el-radio :label="4">补贴</el-radio>
          <el-radio :label="99">付费推广</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="展示顺序" prop="sort">
        <el-input-number
          v-model="formData.sort"
          :min="-9999"
          placeholder="请输入排序序号"
          class="w-80!"
        />
        <el-text class="w-full" size="small" type="info">
          排序序号，数值越大越往后排列，负数排在最前列
        </el-text>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import * as ProductSpuApi from '@/api/mall/product/spu'

/** 产品排序 表单 */
defineOptions({ name: 'RecommendSortForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref<any>({
  id: undefined,
  sort: undefined,
  recommend: undefined
})
const formRules = reactive({
  sort: [{ required: true, message: '展示顺序不能为空', trigger: 'blur' }],
  recommend: [{ required: true, message: '推荐类型不能为空', trigger: 'blur' }]
})
const formRef = ref() // 表单 Ref

/** 打开弹窗 */
const open = async (id?: number | string) => {
  dialogVisible.value = true
  dialogTitle.value = '修改产品推荐类型及排序'
  formType.value = 'update'
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await ProductSpuApi.getSpu(id)
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    await ProductSpuApi.updateRecommendSort(formData.value)
    message.success(t('common.updateSuccess'))
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    sort: undefined,
    recommend: undefined
  }
  formRef.value?.resetFields()
}
</script>
